﻿using System;
using System.Windows;

namespace ClientLauncher.Src.WPFUtils
{
  public class WpfUtils
  {
    public static readonly DependencyProperty FocusOnLoadProperty = DependencyProperty.RegisterAttached("FocusOnLoad", typeof (bool), typeof (WpfUtils), new PropertyMetadata(default(bool), OnFocusOnLoadChanged));
    public static readonly DependencyProperty DialogResultProperty = DependencyProperty.RegisterAttached("DialogResult", typeof (bool?), typeof (WpfUtils), new PropertyMetadata(default(bool), OnDialogResultChanged));

    private static void OnDialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      var window = d as Window;
      if (window != null)
        window.DialogResult = e.NewValue as bool?;
    }

    public static void SetDialogResult(Window target, bool? value)
    {
      target.SetValue(DialogResultProperty, value);
    }

    private static void OnFocusOnLoadChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      var elem = d as FrameworkElement;
      if (elem == null) return;

      if ((bool)e.NewValue)
      {
        elem.Loaded += FocusItem;
      }
      else
      {
        elem.Loaded -= FocusItem;
      }
    }

    private static void FocusItem(object sender, RoutedEventArgs e)
    {
      var elem = sender as FrameworkElement;
      if (elem == null) return;
      elem.Focus();
    }

    public static bool GetFocusOnLoad(UIElement element)
    {
      return (bool)element.GetValue(FocusOnLoadProperty);
    }

    public static void SetFocusOnLoad(UIElement element, bool value)
    {
      element.SetValue(FocusOnLoadProperty, value);
    }
  }

  internal interface IRequestCloseViewModel
  {
    event Action RequestClose;
  }
}